﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

using MyCtp.Model;

using TradeClient.Logic;
using TradeClient.Logic.Entity;
using TradeClient.Logic.TradeCore;

namespace TradeClient.Views
{
    public partial class Quote : Form
    {
        private ChartCandlestick chart;

        public Quote()
        {
            InitializeComponent();
        }

        private void Quote_Load(object sender, EventArgs e)
        {
            InitForm();
            InitQuote();
        }

        private void InitForm()
        {
            splitContainerMain.SplitterDistance = splitContainerMain.Height - 140;
            splitContainerTradeAndAccount.SplitterDistance = splitContainerTradeAndAccount.Width - (int)(splitContainerTradeAndAccount.Width * 0.7);

            dataGridViewCodeList.AutoGenerateColumns = false;
            dataGridViewCodeList.Columns.Add("InstrumentID", "合约代码");
            dataGridViewCodeList.Columns.Add("LastPrice", "最新价");

            dataGridViewCodeList.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewCodeList.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            dataGridViewCodeList.Columns[0].DefaultCellStyle.ForeColor = Color.Yellow;
            dataGridViewCodeList.Columns[1].DefaultCellStyle.ForeColor = Color.White;

            chart = new ChartCandlestick(this.splitContainerPriceAndKLine.Panel2);

            System.Windows.Forms.Timer timer = new Timer();

            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.Text = DateTime.Now.ToLongTimeString();
            FlashPosition();
        }

        public static string msg = "";

        private void FlashPosition()
        {
            listBox1.Items.Clear();

            if( msg != null )
                listBox1.Items.Add(Quote.msg);

            TradeClient.Logic.TradeCore.CtpAccount ctpAccount = AccountManager.GetCtpAccount();

            if(ctpAccount.Information != null )
                listBox1.Items.Add(ctpAccount.Information.Available.ToString());

            if (ctpAccount.Positions != null)
            {
                foreach (CThostFtdcInvestorPositionField field in ctpAccount.Positions)
                    listBox1.Items.Add(field.InstrumentID + "[" + field.PosiDirection.ToString() + "]:" + field.TodayPosition + "," + field.OpenVolume + "," + field.CloseVolume.ToString());
            }

            listBox1.Items.Add("");

            if (ctpAccount.PositionDetails != null)
            {
                foreach (CThostFtdcInvestorPositionDetailField field in ctpAccount.PositionDetails)
                    listBox1.Items.Add(field.TradeID + " " + field.InstrumentID + "[" + field.Direction.ToString() + "]:" + field.Volume + "," + field.CloseVolume.ToString());
            }

            listBox1.Items.Add("");

            if (ctpAccount.PositionCombineDetails != null)
            {
                foreach (CThostFtdcInvestorPositionCombineDetailField field in ctpAccount.PositionCombineDetails)
                    listBox1.Items.Add(field.InstrumentID + "[" + field.Direction.ToString() + "]:" + "," + field.TotalAmt + "," + field.LegMultiple.ToString());
            }

            foreach (Position position in PositionManager.GetInstance().Positions.Values)
            {
                listBox1.Items.Add(position.Id + " 手数：" + position.Volume.ToString());

                /*
                bool f = false;

                foreach (DataGridViewRow row in dataGridViewPosition.Rows)
                {
                    if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() == position.Id)
                    {
                        row.Cells[5].Value = position.Volume;

                        f = true;
                        break;
                    }
                }

                if( f == false )
                    dataGridViewPosition.Rows.Add(position.Id, position.Policy, position.Account, position.Code, position.Direction.ToString(), position.Volume, position.Price);
                */
            }
        }

        private void InitQuote()
        {
            QuoteManager quoteManager = QuoteManager.GetInstance();

            //初始化策略类
            Test policyTest = Test.GetInstance();
            policyTest.AddCtpAccount(AccountManager.GetCtpAccount());
            
            //初始化K线
            foreach (PolicyQuote quote in quoteManager.GetSubscribeQuote())
            {
                KLineSeries kSeries = new KLineSeries(MarketType.Futures, quote.Code, quote.Level, (KLineUnitType)Enum.Parse(typeof(KLineUnitType), quote.Unit));
                kSeries.RegPolicy(policyTest);
                kSeries.PriceUpdate += kSeries_PriceUpdate;

                quoteManager.Add(kSeries);

                dataGridViewCodeList.Rows.Add(quote.Code, "");

                //chart.CreateSeries(quote.Code + "_" + quote.Level + "_" + quote.Unit).ChartArea = chart.ChartAreaName;
            }

            //开始接收行情
            quoteManager.Start();
        }

        private void kSeries_PriceUpdate(KLineSeries series)
        {
            Action ac = () =>
            {
                foreach (DataGridViewRow row in dataGridViewCodeList.Rows)
                {
                    if (row.Cells[0].Value.ToString() == series.Code)
                    {
                        DataGridViewCell cell = row.Cells[1];
                        cell.Value = series[0].Close.ToString();
                        this.currentPrice = series[0].Close;

                        if (cell.Style.ForeColor == Color.White)
                            cell.Style.ForeColor = Color.Gray;
                        else
                            cell.Style.ForeColor = Color.White;

                        break;
                    }
                }
                /*
                Series chartSeries = chart.GetSeries(series.Code + "_" + series.Level + "_" + series.Unit);

                KLine k = series[0];

                if (chartSeries.Points.Count == 0)
                    chartSeries.Points.AddXY(k.OpenTime, k.High, k.Low, k.Open, k.Close);
                else
                    chartSeries.Points[chartSeries.Points.Count - 1].SetValueY(k.High, k.Low, k.Open, k.Close);

                //chart.FlashView();

                this.currentPrice = k.Close;
                */
            };

            this.Invoke(ac);
        }

        void kSeries_KLineFinished(KLineSeries series)
        {
            Action ac = () =>
            {
                /*
                Series chartSeries = chart.GetSeries(series.Code + "_" + series.Level + "_" + series.Unit);

                KLine k = series[0];
                chartSeries.Points.AddXY(k.OpenTime, k.High, k.Low, k.Open, k.Close);
                */
            };

            this.Invoke(ac);
        }
        
        void kSeries_KLineOpen(KLineSeries series)
        {
            
        }

        private void toolStripButtonTrade_Click(object sender, EventArgs e)
        {
            splitContainerMain.Panel2Collapsed = !splitContainerMain.Panel2Collapsed;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            TradeClient.Logic.TradeCore.CtpAccount ctpAccount = AccountManager.GetCtpAccount();
            ctpAccount.CtpTradeObject.QryTradingAccount();
            //ctpAccount.CtpTradeObject.QryInstrument("");
        }

        private double currentPrice;

        private void btnBuy_Click(object sender, EventArgs e)
        {
            //交易委托单
            CtpOrder ctpOrder = new CtpOrder();

            ctpOrder.Policy = "handle";
            ctpOrder.Market = MarketType.Futures;
            ctpOrder.Code = "ru1301";
            ctpOrder.Level = 1;
            ctpOrder.Unit = KLineUnitType.Minutes;
            ctpOrder.Account = AccountManager.GetCtpAccount().Account;
            ctpOrder.Direction = DirectionType.Buy;
            ctpOrder.AccountObject = AccountManager.GetCtpAccount();
            ctpOrder.OpenClose = OpenCloseType.Open;
            ctpOrder.Price = this.currentPrice + 20;
            ctpOrder.Volume = 1;

            TradeManager.GetInstance().Trade(ctpOrder);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            //交易委托单
            CtpOrder ctpOrder = new CtpOrder();

            ctpOrder.Policy = "handle";
            ctpOrder.Market = MarketType.Futures;
            ctpOrder.Code = "ru1301";
            ctpOrder.Level = 1;
            ctpOrder.Unit = KLineUnitType.Minutes;
            ctpOrder.Account = AccountManager.GetCtpAccount().Account;
            ctpOrder.Direction = DirectionType.Buy;
            ctpOrder.AccountObject = AccountManager.GetCtpAccount();
            ctpOrder.OpenClose = OpenCloseType.Close;
            ctpOrder.Price = this.currentPrice - 20;
            ctpOrder.Volume = 1;

            TradeManager.GetInstance().Trade(ctpOrder);
        }

        private void btnPosition_Click(object sender, EventArgs e)
        {
            TradeClient.Logic.TradeCore.CtpAccount ctpAccount = AccountManager.GetCtpAccount();

            ctpAccount.PositionDetails.Clear();
            ctpAccount.CtpTradeObject.QryInvestorPositionDetail();
        }
    }
}
